#!/usr/bin/env node

/**
 * 风行融媒体客户端守护进程
 * 用于监控客户端进程，在意外退出时自动重启
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

// 配置
const MAX_RESTART_COUNT = 10; // 最大重启次数（10分钟内）
const RESTART_WINDOW = 10 * 60 * 1000; // 10分钟
const RESTART_DELAY = 3000; // 重启延迟：3秒

// 状态
let restartCount = 0;
let restartTimestamps = [];
let clientProcess = null;
let isShuttingDown = false;

// 日志文件
const logDir = path.join(process.env.HOME || process.env.USERPROFILE, '.wind-share-media', 'logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}
const logFile = path.join(logDir, 'watchdog.log');

// 日志函数
function log(message) {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] ${message}\n`;
  
  console.log(logMessage.trim());
  
  try {
    fs.appendFileSync(logFile, logMessage);
  } catch (error) {
    console.error('写入日志失败:', error);
  }
}

// 清理过期的重启记录
function cleanupRestartHistory() {
  const now = Date.now();
  restartTimestamps = restartTimestamps.filter(timestamp => 
    now - timestamp < RESTART_WINDOW
  );
}

// 检查是否可以重启
function canRestart() {
  cleanupRestartHistory();
  
  if (restartTimestamps.length >= MAX_RESTART_COUNT) {
    log(`❌ 重启次数过多（${MAX_RESTART_COUNT}次/${RESTART_WINDOW/1000/60}分钟），停止自动重启`);
    return false;
  }
  
  return true;
}

// 启动客户端
function startClient() {
  if (isShuttingDown) {
    log('⚠️ 正在关闭守护进程，跳过启动');
    return;
  }

  log('🚀 启动风行融媒体客户端...');
  
  // 启动 Electron 应用
  const electronPath = require('electron');
  const appPath = path.join(__dirname, 'src/main/index.js');
  
  clientProcess = spawn(electronPath, [appPath], {
    stdio: 'inherit',
    env: process.env
  });
  
  log(`✅ 客户端进程已启动 (PID: ${clientProcess.pid})`);
  
  // 监听进程退出
  clientProcess.on('exit', (code, signal) => {
    log(`⚠️ 客户端进程退出 (退出码: ${code}, 信号: ${signal})`);
    clientProcess = null;
    
    // 如果不是正常退出，尝试重启
    if (code !== 0 && !isShuttingDown) {
      handleCrash(code, signal);
    } else if (code === 0) {
      log('✅ 客户端正常退出');
      process.exit(0);
    }
  });
  
  // 监听进程错误
  clientProcess.on('error', (error) => {
    log(`❌ 客户端进程错误: ${error.message}`);
    clientProcess = null;
    handleCrash(null, null);
  });
}

// 处理崩溃
function handleCrash(code, signal) {
  if (isShuttingDown) {
    return;
  }

  log(`💥 检测到客户端崩溃 (退出码: ${code}, 信号: ${signal})`);
  
  if (!canRestart()) {
    log('❌ 无法继续重启，守护进程退出');
    process.exit(1);
    return;
  }
  
  // 记录重启时间
  restartTimestamps.push(Date.now());
  restartCount++;
  
  log(`🔄 准备重启客户端... (第 ${restartCount} 次重启)`);
  log(`⏳ 等待 ${RESTART_DELAY/1000} 秒后重启...`);
  
  // 延迟重启
  setTimeout(() => {
    if (!isShuttingDown) {
      startClient();
    }
  }, RESTART_DELAY);
}

// 优雅关闭
function gracefulShutdown(signal) {
  if (isShuttingDown) {
    return;
  }
  
  isShuttingDown = true;
  log(`📴 收到 ${signal} 信号，准备关闭...`);
  
  if (clientProcess) {
    log('🛑 正在关闭客户端进程...');
    clientProcess.kill('SIGTERM');
    
    // 5秒后强制关闭
    setTimeout(() => {
      if (clientProcess) {
        log('⚠️ 客户端进程未响应，强制关闭');
        clientProcess.kill('SIGKILL');
      }
      process.exit(0);
    }, 5000);
  } else {
    process.exit(0);
  }
}

// 监听关闭信号
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

// 未捕获的异常
process.on('uncaughtException', (error) => {
  log(`❌ 守护进程异常: ${error.message}`);
  log(error.stack);
  gracefulShutdown('EXCEPTION');
});

// 主程序
log('========================================');
log('🛡️ 风行融媒体守护进程启动');
log(`📁 日志文件: ${logFile}`);
log(`🔄 最大重启次数: ${MAX_RESTART_COUNT}次/${RESTART_WINDOW/1000/60}分钟`);
log(`⏱️ 重启延迟: ${RESTART_DELAY/1000}秒`);
log('========================================');

// 启动客户端
startClient();
